public class BInarySearchNoRecur {
    public static void main(String[] args) {
        int[] array = {1,4,7,34,86,124};
        int result = binarySearchNoRecur(array,4);
        System.out.println("result = " + result);
    }

    /**
     * 非迭代二分法查找
     * @param array:待查找数组
     * @param num:查找的数组元素的值
     * @return:该元素在数组中的位置
     */
    public static int binarySearchNoRecur(int[] array,int num){
        int left = 0;
        int right = array.length - 1;
        //注意这里是小于等于
        while(left <= right){
            int mid = (left + right) / 2;
            if(array[mid] == num){
                return mid;
            }else if(array[mid] < num){
                left = mid + 1;
            }else{
                right = mid - 1;
            }
        }
        return -1;
    }
}
